package com.czk.netty.nio.chat.practice;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/8 15:53
 */
public class NioGroupChatClient {
    /**
     * 选择器
     */
    private Selector selector;
    /**
     * ip
     */
    private final String HOST = "127.0.0.1";
    /**
     * 端口
     */
    private final int PORT = 8080;
    /**
     * 客户端
     */
    private SocketChannel socketChannel;
    /**
     *
     */
    private String username;

    /**
     * @throws IOException
     */
    public NioGroupChatClient() throws IOException {
        selector = Selector.open();
        socketChannel = SocketChannel.open();
        // 链接
        socketChannel.connect(new InetSocketAddress(HOST, PORT));
        // 配置非阻塞
        socketChannel.configureBlocking(false);
        // 设置注册
        // 注册事件
        socketChannel.register(selector, SelectionKey.OP_READ);
        // 拿到主机名
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + "准备好了");
    }

    /**
     * 发送消息
     *
     * @param message
     */
    public void sendMessage(String message) {
        try {
            socketChannel.write(ByteBuffer.wrap(message.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取消息
     *
     * @throws IOException
     */
    public void readMessage() throws IOException {
        // 拿到连接数
        int select = selector.select();
        if (select > 0) {
            // 读取数据
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            // 拿到迭代器
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            // 遍历
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                // 查看状态
                if (selectionKey.isReadable()) {
                    // 拿到通道
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    // 配置非阻塞
                    channel.configureBlocking(false);
                    // 创建缓冲区
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    // 读取数据
                    channel.read(byteBuffer);
                    // 转为字符串
                    System.out.println(new String(byteBuffer.array()));
                }
            }
            iterator.remove();
        }
    }

    public static void main(String[] args) throws IOException {
        NioGroupChatClient chatClient = new NioGroupChatClient();
        // 线程接收
        new Thread(() -> {
            while (true){
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    chatClient.readMessage();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            chatClient.sendMessage(scanner.next());
        }
    }
}
